#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#define PATH "."
#define FILENAME "fifo"
#include "comm.h"
class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoName = _path + "/" + _name;
        int n = mkfifo(_fifoName.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "mkfifo create success!" << std::endl;
        }
    }
    ~NamedFifo()
    {
        int n = unlink(_fifoName.c_str());
        if (n < 0)
        {
            ERR_EXIT("unlink");
        }
        else
        {
            std::cout << "unlink success!" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoName;
};

class FileOpt
{
public:
    FileOpt(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoName = _path + "/" + _name;
    }
    // 打开管道
    void OpenForRead()
    {
        _fd = open("fifo", O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open file to read");
        }
        else
        {
            std::cout << "open fifo success" << std::endl;
        }
    }
    void OpenForWrite()
    {
        _fd = open("fifo", O_WRONLY | O_TRUNC);
        if (_fd < 0)
        {
            ERR_EXIT("open file to write");
        }
        else
        {
            std::cout << "open file to write success" << std::endl;
        }
    }
    bool Wait()
    {
        char c;
        int number = read(_fd, &c, 1);
        if (number > 0)
        {
            printf("醒来: %d\n", number);
            return true;
        }
        else
        {
            return false;
        }
    }
    void WakeUp()
    {
        // 写入操作
        char c = 'c';
        int n = write(_fd, &c, 1);
        printf("尝试唤醒: %d\n", n);
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOpt()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoName;
    int _fd;
};
